package org.herrdommel.preference;

import java.util.Calendar;
import java.util.Date;

import org.herrdommel.wakemeup.model.Alarm;

import android.content.Context;
import android.preference.DialogPreference;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TimePicker;

/** A preference type that allows a user to choose a time */
public class TimePickerPreference extends DialogPreference {

	/** The calendar instance used for this preference */
	private final Calendar cal = Calendar.getInstance();

	/** The time picker used for this preference */
	private TimePicker tp = null;

	public TimePickerPreference(final Context context, final AttributeSet attrs) {
		super(context, attrs);
		initialize();
	}

	public TimePickerPreference(final Context context, final AttributeSet attrs, final int defStyle) {
		super(context, attrs, defStyle);
		initialize();
	}

	@Override
	protected View onCreateDialogView() {

		tp = new TimePicker(getContext());
		tp.setIs24HourView(DateFormat.is24HourFormat(getContext()));

		tp.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY));
		tp.setCurrentMinute(cal.get(Calendar.MINUTE));

		return tp;
	}

	@Override
	protected void onDialogClosed(final boolean positiveResult) {
		if (positiveResult) {
			tp.clearFocus();
			cal.set(Calendar.HOUR_OF_DAY, tp.getCurrentHour());
			cal.set(Calendar.MINUTE, tp.getCurrentMinute());
			final String result = Alarm.SDF.format(cal.getTime());
			persistString(result);
			callChangeListener(result);
		}
	}

	/**
	 * Return the time of this preference as a string.
	 * @return the time as string
	 */
	public String getTime() {
		return DateFormat.getTimeFormat(getContext()).format(cal.getTime());
	}

	/**
	 * Sets the time for this preference
	 * @param time the time in form of a {@link Date}
	 */
	public void setTime(final Date time) {
		cal.setTime(time);
	}

	/** Initializes this dialog, e.g. sets its persistant state to true. */
	private void initialize() {
		setPersistent(true);
	}

}